<template>
  <el-drawer v-model="visible" :title="title" size="40%" destroy-on-close>
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="角色名称" prop="FName">
        <el-input v-model="formData.FName" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="角色编码" prop="FCode">
        <el-input v-model="formData.FCode" placeholder="请输入角色编码" />
      </el-form-item>
      <el-form-item label="角色描述" prop="FDescription">
        <el-input v-model="formData.FDescription" type="textarea" placeholder="请输入角色描述" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { createRole, updateRole } from "@/api/modules/permission";

const emit = defineEmits(["refresh"]);

const visible = ref(false);
const formRef = ref<FormInstance>();
const title = ref("新增角色");

const formData = reactive({
  FId: "",
  FName: "",
  FCode: "",
  FDescription: ""
});

const rules = reactive<FormRules>({
  FName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  FCode: [{ required: true, message: "请输入角色编码", trigger: "blur" }]
});

const open = (type: "add" | "edit", rowData?: any) => {
  title.value = type === "add" ? "新增角色" : "编辑角色";
  if (type === "edit" && rowData) {
    Object.assign(formData, rowData);
  } else {
    resetForm();
  }
  visible.value = true;
};

const resetForm = () => {
  formData.FId = "";
  formData.FName = "";
  formData.FCode = "";
  formData.FDescription = "";
};

const handleSubmit = async () => {
  try {
    await formRef.value?.validate();

    if (formData.FId) {
      await updateRole(formData.FId, formData);
      ElMessage.success("更新成功");
    } else {
      await createRole(formData);
      ElMessage.success("创建成功");
    }

    visible.value = false;
    emit("refresh");
  } catch {
    // 验证失败
  }
};

defineExpose({ open });
</script>
